package com.yourbatis.syntax;

import com.yourbatis.interpreter.Environment;

import java.util.List;

public class FunctionObject {
    final List<String> parameters;
    final BlockStatement body;

    public FunctionObject(List<String> parameters, BlockStatement body) {
        this.parameters = parameters;
        this.body = body;
    }

    public Object call(List<Object> arguments) {
        // 创建新作用域
        Environment.enterScope();
        try {
            // 绑定参数
            for (int i = 0; i < parameters.size(); i++) {
                Environment.define(parameters.get(i), arguments.get(i));
            }
            // 执行函数体
            body.execute();
            return Environment.getReturnValue();
        } finally {
            Environment.exitScope();
        }
    }
}
